 

package com.zdkj.subway.check.controller.subwayRat.swAuTvm;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.entity.Page;
import com.zdkj.subway.check.entity.SwAuTvmAmountDefference;
import com.zdkj.subway.check.entity.SwAuTvmNotice;
import com.zdkj.subway.check.entity.SwAuTvmShort;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuTvmAmountDefferenceMapper;
import com.zdkj.subway.check.mapper.SwAuTvmNoticeMapper;
import com.zdkj.subway.check.mapper.SwAuTvmShortMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwAuTvmShortService;
import com.zdkj.subway.check.util.DateFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.*;


/**
 * 售票员补款
 *
 * @author zhangxy
 * @date 2024-12-18 14:02:32
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swautvmshort" )
@Api(value = "swautvmshort", tags = "售票员补款管理")
public class SwAuTvmShortController {

    private final SwAuTvmShortService swAuTvmShortService;
    private final SwAuTvmShortMapper swAuTvmShortMapper;

    @Autowired
    private SwAuTvmAmountDefferenceMapper swAuTvmAmountDefferenceMapper;
    @Autowired
    private CommonController commonController;
    @Autowired
    private SwAuTvmNoticeMapper swAuTvmNoticeMapper;

    @RequestMapping("/getSwAuTvmShortList")
    @ApiOperation(value = "TVM补款确认通知 列表", notes = "TVM补款确认通知 列表")
    public Result getSwAuTvmShortList(@RequestBody JSONObject jsonObject) {
        return swAuTvmShortService.getSwAuTvmShortList(jsonObject);
    }

    @RequestMapping("/getSwAuTvmShort")
    @ApiOperation(value = "获取TVM补款", notes = "获取TVM补款")
    public Page getSwAuTvmShort(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swAuTvmShort = swAuTvmShortService.getSwAuTvmShort(param);
        page.setData(swAuTvmShort, true);
        return page;
    }

    @RequestMapping("/buKuanSwAuTvmShort")
    @ApiOperation(value = "TVM补款确认通知 补款", notes = "TVM补款确认通知 补款")
    public Result buKuanSwAuTvmShort(@RequestBody JSONObject jsonObject){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            SwAuTvmShort swAuTvmShort = JSONObject.parseObject(jsonObject.toJSONString(), SwAuTvmShort.class);
            swAuTvmShort.setIsSupPayment(1);
            LocalDate supPaymentTimelimit = DateFormat.dateTOLocalDate(swAuTvmShort.getSupPaymentTimelimit());
            LocalDate newLocalDate = DateFormat.dateTOLocalDate(new Date());
            if(supPaymentTimelimit.compareTo(newLocalDate)>=0){
                swAuTvmShort.setIsLimitSuppay("1");
            }else{
                swAuTvmShort.setIsLimitSuppay("0");
            }
            if(swAuTvmShort.getSupPaymentTime()!=null){
                swAuTvmShort.setAccountTime(swAuTvmShort.getSupPaymentTime());//入账日期
            }
            swAuTvmShortMapper.updateById(swAuTvmShort);
            Integer diffId = swAuTvmShort.getDiffId();
            SwAuTvmAmountDefference swAuTvmAmountDefference = new SwAuTvmAmountDefference();
            swAuTvmAmountDefference.setId(diffId);
            swAuTvmAmountDefference.setSuppState("3");//0；未加入补款 1；未补款 3；已补款
            swAuTvmAmountDefferenceMapper.updateById(swAuTvmAmountDefference);
            SwAuTvmNotice swAuTvmNotice = new SwAuTvmNotice();
            swAuTvmNotice.setIsSupPayment(1);
            UpdateWrapper<SwAuTvmNotice> objectUpdateWrapper = new UpdateWrapper<>();
            objectUpdateWrapper.eq("RELATIONID",diffId);
            swAuTvmNoticeMapper.update(swAuTvmNotice, objectUpdateWrapper);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("补款失败");
        }
        return res;
    }

    @RequestMapping("/getSwAuTvmShortLimit")
    @ApiOperation(value = "票卡信息查询列表", notes = "票卡信息查询列表")
    public Page getSwAuTvmShortLimit(Page page,@RequestParam Map<String,String> param){
        Map req = new HashMap();
        List<Integer> ids = new ArrayList<>();
        if(null != param.get("ids")){
            ids = (List)JSONObject.parseArray(String.valueOf(param.get("ids")));
        }else{
            return page;
        }
        List swAuTvmShortList = new ArrayList();
        for(Integer id : ids){
            req.put("id",id);
            List<Map<String, Object>> swAuTvmShort = swAuTvmShortMapper.getSwAuTvmShort(req);
            swAuTvmShortList.addAll(swAuTvmShort);
        }
        page.setData(swAuTvmShortList,true);
        return page;
    }

    @RequestMapping("/updateSwAuTvmShortLimit")
    @ApiOperation(value = "TVM补款设置入账日期 和 补款期限", notes = "TVM补款设置入账日期 和 补款期限")
    public Result updateSwAuTvmShortLimit(@RequestParam Map<String,String> param) throws Exception {
        if(null != param.get("list")){
            JSONArray list = JSONObject.parseArray(param.get("list"));
            if(null != list){
                List<SwAuTvmShort> swAuTvmShorts = JSONObject.parseArray(list.toJSONString(), SwAuTvmShort.class);
                for (SwAuTvmShort swAuTvmShort : swAuTvmShorts) {
                    if(ObjectUtil.isNotEmpty(swAuTvmShort.getAccountTime())){
                        // accountTime  年-月-日  supPaymentTime  年月日小时分秒
                        // if accountTime不等于空  把 accountTime更新到supPaymentTime里的年月日里 小时分秒保留
                        Date accountTime = swAuTvmShort.getAccountTime();
                        String accountTimeStr = DateFormat.date_ex_str(accountTime, "yyyy-MM-dd");
                        String accountDateStr = accountTimeStr.substring(0, 10);

                        Date supPaymentTime = swAuTvmShort.getSupPaymentTime();
                        String supPaymentTimeStr = DateFormat.date_ex_str(supPaymentTime, "yyyy-MM-dd");
                        String supPaymentDateStr = supPaymentTimeStr.substring(supPaymentTimeStr.length()-9);

                        //拼接
                        String newDateTime = accountDateStr+supPaymentDateStr;
                        swAuTvmShort.setSupPaymentTime(DateFormat.stringToDateFormat(newDateTime));
                    }

                    swAuTvmShortMapper.updateById(swAuTvmShort);
                }
            }
        }
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    @RequestMapping("/updateSwAuTvmShort")
    @ApiOperation(value = "TVM补款信息下发通知", notes = "TVM补款信息下发通知")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuTvmShort(@RequestBody Map<String,Object> param){
        PigxUser user = SecurityUtils.getUser();
        try {
            if(null != param.get("list")){
                List<Map<String,Object>> list = (List)JSONObject.parseArray(String.valueOf(param.get("list")));
                for(Map<String,Object> m : list){
                    String id = String.valueOf(m.get("id"));
                    String supPaymentLimit = String.valueOf(m.get("supPaymentLimit"));
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(new Date());
                    calendar.add(calendar.DATE,Integer.valueOf(supPaymentLimit));
                    SwAuTvmShort swAuTvmShort = swAuTvmShortMapper.selectById(Long.valueOf(id));
                    if(ObjectUtil.isNotEmpty(swAuTvmShort)){
                        swAuTvmShort.setIsNotice(1);
                        swAuTvmShort.setNoticeTime(new Date());
                        swAuTvmShort.setNoticeName(user.getNikeName());
                        swAuTvmShort.setSupPaymentTimelimit(calendar.getTime());
                        swAuTvmShortMapper.updateById(swAuTvmShort);
                        Integer diffId = swAuTvmShort.getDiffId();
                        SwAuTvmAmountDefference swAuTvmAmountDefference = new SwAuTvmAmountDefference();
                        swAuTvmAmountDefference.setId(diffId);
                        swAuTvmAmountDefference.setSuppState("1");//0；未加入补款 1；未补款 3；已补款
                        swAuTvmAmountDefferenceMapper.updateById(swAuTvmAmountDefference);
                    }
                }
                commonController.innerBatch(param);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    @RequestMapping("/batchBuKuanSwAuTvmShort")
    @ApiOperation(value = "TVM补款确认通知 批量补款", notes = "TVM补款确认通知 批量补款")
    public Result batchBuKuanSwAuTvmShort(String rows) {
        Result res=new Result(ResultDetailMsg.OK);
        try {
            JSONArray jsonArray=JSONArray.parseArray(rows);
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                SwAuTvmShort swAuTvmShort = JSONObject.parseObject(jsonObject.toJSONString(), SwAuTvmShort.class);
                swAuTvmShort.setIsSupPayment(1);
                if(swAuTvmShort.getSupPaymentTimelimit().compareTo(new Date())>=0){
                    swAuTvmShort.setIsLimitSuppay("1");
                }else{
                    swAuTvmShort.setIsLimitSuppay("0");
                }
                if(swAuTvmShort.getSupPaymentTime()!=null){
                    swAuTvmShort.setAccountTime(swAuTvmShort.getSupPaymentTime());//入账日期
                }
                swAuTvmShortMapper.updateById(swAuTvmShort);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("补款失败");
        }
        return res;
    }

    /**
     * 通过id查询售票员补款
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Integer id) {
        return R.ok(swAuTvmShortService.getById(id));
    }

    /**
     * 新增售票员补款
     * @param swAuTvmShort 售票员补款
     * @return R
     */
    @ApiOperation(value = "新增售票员补款", notes = "新增售票员补款")
    @SysLog("新增售票员补款" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('generator_swautvmshort_add')" )
    public R save(@RequestBody SwAuTvmShort swAuTvmShort) {
        return R.ok(swAuTvmShortService.save(swAuTvmShort));
    }

    /**
     * 修改售票员补款
     * @param swAuTvmShort 售票员补款
     * @return R
     */
    @ApiOperation(value = "修改售票员补款", notes = "修改售票员补款")
    @SysLog("修改售票员补款" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('generator_swautvmshort_edit')" )
    public R updateById(@RequestBody SwAuTvmShort swAuTvmShort) {
        return R.ok(swAuTvmShortService.updateById(swAuTvmShort));
    }

    /**
     * 通过id删除售票员补款
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除售票员补款", notes = "通过id删除售票员补款")
    @SysLog("通过id删除售票员补款" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('generator_swautvmshort_del')" )
    public R removeById(@PathVariable Integer id) {
        return R.ok(swAuTvmShortService.removeById(id));
    }

}
